package com.atguigu.flink.chapter08;

import com.atguigu.flink.bean.OrderEvent;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/8/17 15:36
 */
public class Flink06_Project_High_Order {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        
        WatermarkStrategy<OrderEvent> wms = WatermarkStrategy
            .<OrderEvent>forBoundedOutOfOrderness(Duration.ofSeconds(20))
            .withTimestampAssigner(new SerializableTimestampAssigner<OrderEvent>() {
                @Override
                public long extractTimestamp(OrderEvent element, long recordTimestamp) {
                    return element.getEventTime();
                }
            });
        
        env
            .readTextFile("input/OrderLog.csv")
            .map(line -> {
                String[] datas = line.split(",");
                return new OrderEvent(
                    Long.valueOf(datas[0]),
                    datas[1],
                    datas[2],
                    Long.parseLong(datas[3]) * 1000);
                
            })
            .assignTimestampsAndWatermarks(wms)
            .keyBy(OrderEvent::getOrderId)
            .process(new KeyedProcessFunction<Long, OrderEvent, String>() {
                
                private ValueState<OrderEvent> createState;
                private ValueState<OrderEvent> payState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    createState = getRuntimeContext()
                        .getState(new ValueStateDescriptor<OrderEvent>("createState", OrderEvent.class));
                    payState = getRuntimeContext()
                        .getState(new ValueStateDescriptor<OrderEvent>("payState", OrderEvent.class));
                }
    
                @Override
                public void onTimer(long timestamp,
                                    OnTimerContext ctx,
                                    Collector<String> out) throws Exception {
                    if(createState.value() != null){
                        out.collect(createState.value().getOrderId() + " 只有创建没有支付...");
                    }else{
                        out.collect(payState.value().getOrderId() + " 只有支付没有创建...");
                    }
              }
    
                @Override
                public void processElement(OrderEvent orderEvent,
                                           Context ctx,
                                           Collector<String> out) throws Exception {
                    if (createState.value() == null && payState.value() == null) {
                        ctx.timerService().registerEventTimeTimer(orderEvent.getEventTime() + 46 * 60 * 1000);
                    } else {
                        
                        Long ts = createState.value() == null ? payState.value().getEventTime() : createState.value().getEventTime();
                        
                        ctx.timerService().deleteEventTimeTimer(ts + 46 * 60 * 1000);
                    }
                    
                    // 来一条数据, 先看对方是否在, 如果在, 再判断时间是否在要求的时间内.
                    // 对方不在, 就把自己缓存到状态中
                    
                    String eventType = orderEvent.getEventType();
                    if ("create".equals(eventType)) {
                        if (payState.value() == null) {
                            // 把这次存入到状态
                            createState.update(orderEvent);
                            
                        } else if (payState.value().getEventTime() - orderEvent.getEventTime() <= 45 * 60 * 1000) {
                            out.collect(orderEvent.getOrderId() + " 被正常创建和支付...");
                        } else {
                            out.collect(orderEvent.getOrderId() + " 被超时支付, 请检测系统漏洞...");
                        }
                    } else {
                        if (createState.value() == null) {
                            // 把这次存入到状态
                            payState.update(orderEvent);
                        } else if (orderEvent.getEventTime() - createState.value().getEventTime() <= 45 * 60 * 1000) {
                            out.collect(orderEvent.getOrderId() + " 被正常创建和支付...");
                        } else {
                            out.collect(orderEvent.getOrderId() + " 被超时支付, 请检测系统漏洞...");
                        }
                    }
                    
                }
            })
            .print();
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
/*
 
 
 */
